import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { getUserList } from '../api/user'


// React Redux Toolkit 
// https://www.bilibili.com/video/BV1ZP411d7v9

// 异步请求
export const userListQuery = createAsyncThunk('user/query', async (page) => {
    console.log('UserQuery createAsyncThunk page=', page)
    return await getUserList(page)
})



// 异步请求方式2
export const addUserAsync = (payload) => {
    console.log('userListQuery2 payload=', payload)

    return async (dispatch, getState) => {
        return new Promise((resol, reject) => {
            setTimeout(() => {
                dispatch(addUser(payload))
            }, 3000);
        })
    }
}


export const userSlice = createSlice({
    name: 'user',

    initialState: {
        pageTitle: "User",
        users: [
            {
                id: Date.now() + Math.random(),
                first_name: "Echo",
                last_name: 'Bluth',
                avatar : "https://reqres.in/img/faces/1-image.jpg",
                email: "george.bluth@reqres.in"
            },
            {
                id: Date.now() + Math.random(),
                first_name: "Echo2",
                last_name: 'Bluth2',
                avatar : "https://reqres.in/img/faces/1-image.jpg",
                email: "george.bluth@reqres.in"
            }
        ]
    },

    // 同步方法的action操作
    reducers: {

        addUser: (state, action) => {
            console.log('addUser action=', action)
            state.users.unshift(
                action.payload
            )
        },

        setPageTitle: (state, action) => {
            state.pageTitle = action.payload.title
        },
    },


    // 异步方法操作
    extraReducers: (builder) => {
        builder.addCase(userListQuery.fulfilled, (state, action) => {
            // console.log('extraReducers userListQuery action=', action)

            state.users.unshift(
                ...action.payload?.data || []
            )
        })
    }
})

// headerSlice 有2个属性 actions，reducer
export const { addUser, setPageTitle, removeNotificationMessage, showNotification } = userSlice.actions

export default userSlice.reducer
